import React, { useState, useEffect } from 'react'
import './App.css'
import { MapChart } from './components/MapChart'
import { MetricsPanel } from './components/MetricsPanel'
import { ChartPanel } from './components/ChartPanel'

// 定义省份数据结构
export interface ProvinceData {
  value: number;
  cpuUsage: number;
  memoryUsage: number;
  networkTraffic: number;
  storage: number;
  processingPower: string;
  computeNodes: number;
}

// 定义配置接口
interface AppConfig {
  layout: {
    header: {
      visible: boolean;
      title: string;
      showTime: boolean;
    };
    modules: {
      map: {
        visible: boolean;
        width: number;
        title: string;
      };
      metrics: {
        visible: boolean;
        width: number;
        title: string;
      };
      charts: {
        visible: boolean;
        width: number;
        title: string;
      };
    };
  };
  theme: {
    background: string;
    panelBackground: string;
    textColor: string;
    secondaryTextColor: string;
  };
  texts: {
    cpuUsageLabel: string;
    memoryUsageLabel: string;
    networkTrafficLabel: string;
    storageLabel: string;
    processingPowerLabel: string;
    computeNodesLabel: string;
  };
}

function App() {
  const [currentTime, setCurrentTime] = useState(new Date())
  const [config, setConfig] = useState<AppConfig | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  // 添加选中省份的状态
  const [selectedProvince, setSelectedProvince] = useState<{
    name: string;
    data: ProvinceData | null;
  } | null>(null)
  
  // 加载应用配置
  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const response = await fetch('/data/config.json')
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`)
        }
        const data = await response.json()
        setConfig(data)
        
        // 应用主题
        if (data.theme) {
          document.documentElement.style.setProperty('--app-background', data.theme.background)
          document.documentElement.style.setProperty('--panel-background', data.theme.panelBackground)
          document.documentElement.style.setProperty('--text-color', data.theme.textColor)
          document.documentElement.style.setProperty('--secondary-text-color', data.theme.secondaryTextColor)
        }
        
        setLoading(false)
      } catch (err) {
        console.error('加载配置失败:', err)
        setError('加载配置失败，请检查网络连接')
        setLoading(false)
      }
    }

    fetchConfig()
  }, [])

  // 时钟更新
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date())
    }, 1000)

    return () => {
      clearInterval(timer)
    }
  }, [])

  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  }

  // 处理省份选择事件
  const handleProvinceSelect = (provinceName: string, provinceData: ProvinceData | null) => {
    setSelectedProvince({
      name: provinceName,
      data: provinceData
    })
  }

  if (loading) {
    return (
      <div className="dashboard loading-container">
        <div className="loading">加载配置中...</div>
      </div>
    )
  }

  if (error || !config) {
    return (
      <div className="dashboard error-container">
        <div className="error">{error || '无法加载配置'}</div>
      </div>
    )
  }

  // 根据配置动态设置模块宽度
  const getModuleStyle = (moduleConfig: { width: number }) => {
    return {
      flex: moduleConfig.width
    }
  }

  return (
    <div className="dashboard">
      {config.layout.header.visible && (
        <header>
          <h1>{config.layout.header.title}</h1>
          <div className="header-info">
            <span>中国</span> | <span>世界</span> | 
            {config.layout.header.showTime && (
              <span className="timestamp">{formatDate(currentTime)}</span>
            )}
          </div>
        </header>
      )}
      <main>
        {config.layout.modules.map.visible && (
          <div 
            className="map-chart" 
            style={getModuleStyle(config.layout.modules.map)}
          >
            <MapChart onProvinceSelect={handleProvinceSelect} />
          </div>
        )}
        {config.layout.modules.metrics.visible && (
          <div 
            className="metrics-panel" 
            style={getModuleStyle(config.layout.modules.metrics)}
          >
            <MetricsPanel 
              textLabels={config.texts} 
              selectedProvince={selectedProvince}
            />
          </div>
        )}
        {config.layout.modules.charts.visible && (
          <div 
            className="chart-panel" 
            style={getModuleStyle(config.layout.modules.charts)}
          >
            <ChartPanel />
          </div>
        )}
      </main>
    </div>
  )
}

export default App
